﻿using System;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Linq;

using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Net.Mail;

using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.XPath;
using System.Net.Configuration;

using System.Web.Security;
using IFSModel;
using IFSController;
using System.Web.SessionState;

namespace API
{
    public class SSEHandler : IHttpHandler, IRequiresSessionState 
    {

        public string msg { get; set; }
        public string ret { get; set; }

        public string getConn()
        {
            // return ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString.ToString();
            //return "Server=R04019-2K1\\SQLEXPRESS;uid=sa;pwd=1234;database=ifunsoccer"; 
            //return "Data Source=W09390-2K1\\SQLEXPRESS;Initial Catalog=ifunsoccer;Integrated Security=True";
            //return "Data Source=122.155.16.124;;uid=IFN-db;pwd=Ifuns@ccerdb2013;Initial Catalog=IFN-db";
             
             return "Data Source=27.254.67.212;uid=IFN-db;pwd=Ifuns@ccerdb2013;Initial Catalog=IFN-db";


        }

        private DataTable getdata()
        {
            SqlConnection Conn = new SqlConnection(getConn());
            SqlDataAdapter adapter = new SqlDataAdapter();


            string query = "select  * from members";

            adapter.SelectCommand = new SqlCommand(query, Conn);

            DataTable dt = new DataTable();

            Conn.Open();
            try
            {
                adapter.Fill(dt);
            }
            catch (Exception ex)
            {
                return dt = null;
            }

            finally
            {
                Conn.Close();
            }

            return dt;

        }

       
        private DataTable getrankingall(int viewby = 0)
        {
            connection con = new connection();
            SqlConnection Conn = new SqlConnection(connection.getConn());
            SqlDataAdapter adapter = new SqlDataAdapter();
             
            string query = "";


            if (viewby == 0)
            { 
                query = @"SELECT memid,FirstName,LastName,(curent_point+ curent_star) point_star,curent_point,curent_star, 
                        DENSE_RANK() OVER (ORDER BY  curent_point  DESC) AS RankTotal , 
                        (select SUM(p.Mpt_Cal_Point) Mpt_Cal_Point from Members_point_tran p  where p.typeid = 3 and p.memid = a.memid 
                        and datepart(month,p.Createdate) = datepart(month,getdate()) group by p.memid ) pointperthismonth ,1 sorting
                        FROM (select memid,curent_point,curent_star,FirstName,LastName from members ) as a order by RankTotal ";

                // new 

                //select count(p.mptid) totalplay,m.memid,m.FirstName,m.LastName, m.curent_star,m.curent_point,  
                //DENSE_RANK() OVER (ORDER BY m.curent_point  DESC) AS RankTotal,
                //(select SUM(p.Mpt_Cal_Point) Mpt_Cal_Point from Members_point_tran p  where p.typeid = 3 and p.memid = m.memid 
                //and datepart(month,p.Createdate) = datepart(month,getdate()) group by p.memid ) pointperthismonth
                //from Members_point_tran p 
                //inner join members m on p.memid = m.memid 
                //group by  m.memid,m.FirstName,m.LastName,m.curent_star,m.curent_point
                  
            }
            else if (viewby == 1) // per month
            {
                query = @"select count(p.mptid) totalplay,m.memid,m.FirstName,m.LastName, m.curent_star,SUM(p.Mpt_Cal_Point) curent_point, 
                         SUM(p.Mpt_Cal_Point) pointperthismonth ,   
                         DENSE_RANK() OVER (ORDER BY  SUM(p.Mpt_Cal_Point)  DESC) AS RankTotal
                         from Members_point_tran p 
                         inner join members m on p.memid = m.memid
                         where p.typeid = 3  and datepart(month,p.Createdate) = datepart(month,getdate()) 
                         group by  m.memid,m.FirstName,m.LastName,m.curent_star  ";

            }
            else if (viewby == 2)  
            {
                query = @"SELECT memid,FirstName,LastName,(curent_point+ curent_star) point_star,curent_point,curent_star, 
                        DENSE_RANK() OVER (ORDER BY  curent_star  DESC) AS RankTotal , 
                        (select SUM(p.Mpt_Cal_Point) Mpt_Cal_Point from Members_point_tran p  where p.typeid = 3 and p.memid = a.memid 
                        and datepart(month,p.Createdate) = datepart(month,getdate()) group by p.memid ) pointperthismonth ,1 sorting
                        FROM (select memid,curent_point,curent_star,FirstName,LastName from members ) as a order by RankTotal ";

            }

            adapter.SelectCommand = new SqlCommand(query, Conn); 

            DataTable dt = new DataTable();

            Conn.Open();
            try
            {
                adapter.Fill(dt);  
                //dt.DefaultView.Sort = "sorting ASC";
            }
            catch
            {
                Conn.Close();
                dt = null;
            }
            finally
            {
                Conn.Close();
            }


            //DataTable dtn = new DataTable();
            //dtn.Columns.Add("memid", typeof(string));
            //dtn.Columns.Add("FirstName", typeof(string));
            //dtn.Columns.Add("LastName", typeof(string));
            //dtn.Columns.Add("point_star", typeof(string));
            //dtn.Columns.Add("curent_point", typeof(string));
            //dtn.Columns.Add("curent_star", typeof(string));
            //dtn.Columns.Add("RankTotal", typeof(string));
            //dtn.Columns.Add("pointperthismonth", typeof(string));

            //var i = 0;
            //int RankTotal = 0;

            ////for (int i = 0; i <= count; i++)
            //foreach (DataRow dr in dt.Rows)
            //{
            //    DataRow row;
            //    row = dtn.NewRow();

            //    RankTotal = Convert.ToInt32(dr["curent_star"].ToString());

            //    if ( (i + 1) <= dt.Rows.Count){
            //        if (Convert.ToInt32(dt.Rows[i]["RankTotal"]) == Convert.ToInt32(dt.Rows[i + 1]["RankTotal"]))
            //        {
            //            //if (Convert.ToDouble(dt.Rows[i]["curent_point"]) > Convert.ToDouble(dt.Rows[i + 1]["curent_point"]))
            //            //{ 
            //            //}

            //            DataTable dt2 = dt.Select("RankTotal = " + dt.Rows[i]["RankTotal"].ToString()).CopyToDataTable();

            //            foreach (DataRow dr2 in dt2.Rows)
            //            {
            //                if (Convert.ToInt32(dr["curent_star"].ToString()) > Convert.ToInt32(dt2.Rows[i]["curent_star"].ToString()))
            //                { 
            //                }
            //                else {
            //                    RankTotal += 1 ; 
            //                }

            //            } 

            //        }
            //    }

            //    row["memid"] = dr["menu_url"].ToString();
            //    row["FirstName"] = dr["menu_url"].ToString();
            //    row["LastName"] = dr["menu_url"].ToString();
            //    row["point_star"] = dr["menu_url"].ToString();
            //    row["curent_point"] = dr["menu_url"].ToString();
            //    row["curent_star"] = dr["menu_url"].ToString();
            //    row["RankTotal"] = RankTotal;
            //    row["pointperthismonth"] = dr["menu_url"].ToString();

            //    dtn.Rows.Add(row);

            //    i += 1; 
            //}

            return dt;

        }


        private bool savelog(string param)
        {
            SqlConnection Conn = new SqlConnection(getConn());
            SqlDataAdapter adapter = new SqlDataAdapter();

            try
            {

                string strSql = @"INSERT INTO  [ifunsoccer].[logdata] ([data]) VALUES  (@data)";

                SqlCommand cmd = new SqlCommand(strSql, Conn);

                cmd.Parameters.AddWithValue("@data", param);

                Conn.Open();

                cmd.ExecuteScalar();

            }
            catch (Exception ex)
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();

                return false;
            }
            finally
            {
                Conn.Close();
            }

            return true;

        }
        public string GetJson(DataTable dt)
        {

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row = default(Dictionary<string, object>);

            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }

            return serializer.Serialize(rows);
        }

        private bool savecontactus(string Topic, string FirstName, string LastName, string Tell, string Email, string Message, string Ipaddress, Int32 Ptype)
        {
            SqlConnection Conn = new SqlConnection(getConn());
            SqlDataAdapter adapter = new SqlDataAdapter();

            string clientIp = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim();


            try
            {
                string strSql = @"INSERT INTO [dbo].[Contactus]
                                           ([Topic] ,[FirstName],[LastName],[Email],[Tell],[Message],[Ipaddress],[Type])
                                     VALUES (@Topic,@FirstName,@LastName,@Email,@Tell,@Message,@Ipaddress,@Type)";


                SqlCommand cmd = new SqlCommand(strSql, Conn);

                cmd.Parameters.AddWithValue("@Topic", Topic);
                cmd.Parameters.AddWithValue("@FirstName", FirstName);
                cmd.Parameters.AddWithValue("@LastName", LastName);
                cmd.Parameters.AddWithValue("@Email", Email);
                cmd.Parameters.AddWithValue("@Tell", Tell);
                cmd.Parameters.AddWithValue("@Message", Message);
                cmd.Parameters.AddWithValue("@Ipaddress", clientIp);
                cmd.Parameters.AddWithValue("@Type", Ptype);

                Conn.Open();

                cmd.ExecuteScalar();

            }
            catch (Exception ex)
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();

                return false;
            }
            finally
            {
                Conn.Close();
            }

            return true;

        }

        public void ProcessRequest(HttpContext context)
        {

            SqlConnection Conn = new SqlConnection(getConn());

            context.Response.ContentType = "application/json";
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            EmailManager em = new EmailManager();

            string Subject = "";
            string memid = "";

            var MethodName = context.Request.Params["method"];
            DataTable dt = new DataTable();

            GetClolumn GetClolumn = new GetClolumn();

            switch (MethodName)
            {

                case "getRankall":

                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false)
                    {
                        return;
                    }

                    DataTable dtra =  member.getRankall();
                    DataTable dtrm = member.getRankallThisMonth();

                    if (dtra.Rows.Count > 0)
                    {
                        //context.Response.Write(GetJson(dtgetsumaryall));
                        var a = GetJson(dtra);
                        var b = GetJson(dtrm);

                        String bothJson = "[" + a + "," + b + "]"; //Put both objects in an array of 2 elements
                        context.Response.Write(bothJson);

                        return;
                    }

                    break;

                case "getmatchresult":

                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false)
                    {
                        return;
                    }

                    DataTable dtgetmatchresult = new DataTable();

                    dtgetmatchresult = game.getmatchresult(DateTime.Now, 1);

                    if (dtgetmatchresult.Rows.Count > 0)
                    {
                        context.Response.Write(GetJson(dtgetmatchresult));
                        return;
                    }

                    break;

                case "getplaylist":
                    context.Response.ContentType = "text/plain";
                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false && string.IsNullOrEmpty(System.Web.HttpContext.Current.Session["curentUser"].ToString()))
                    {
                        return;
                    }
                    DataTable dtgetplaylist = new DataTable();

                    dtgetplaylist = game.getplaylist(0, DateTime.Now,0);

                    if (dtgetplaylist.Rows.Count > 0)
                    {
                        context.Response.Write(GetJson(dtgetplaylist));
                    }
                    context.Response.End();
                    break;

                case "getplaylisthistory":

                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false && string.IsNullOrEmpty(System.Web.HttpContext.Current.Session["curentUser"].ToString()))
                    {
                        return;
                    }

                    DataTable dtplh = new DataTable();

                    if (!string.IsNullOrEmpty(context.Request.Params["leagueid"]))
                        dtplh = game.getplaylist(0, DateTime.Now, 1, context.Request.Params["leagueid"].ToString()); 
                    else
                        dtplh = game.getplaylist(0, DateTime.Now, 1);


                    if (dtplh.Rows.Count > 0)
                    {
                        context.Response.Write(GetJson(dtplh));
                        return;
                    }

                    break;

                case "getsumaryall":

                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false && string.IsNullOrEmpty(System.Web.HttpContext.Current.Session["curentUser"].ToString()))
                    {
                        return;
                    }

                     DataTable dtgetsumaryall = new DataTable();
                     DataTable dttop10 = new DataTable(null);

                    dtgetsumaryall = member.getsumaryall(); 
                    //dttop10 = member.gettop10latest(); 

                    if (dtgetsumaryall != null || dtgetsumaryall.Rows.Count > 0)
                    {
                        //context.Response.Write(GetJson(dtgetsumaryall));
                        var c = GetJson(dtgetsumaryall);
                        var d = GetJson(dttop10);

                        String bothJson = "[" + c + "," + d + "]"; //Put both objects in an array of 2 elements
                        context.Response.Write(bothJson);

                        return;
                    }
                    else 
                    {

                        DataTable dtc = new DataTable();
                        dtc.Columns.Add("curent_point", typeof(int));
                        dtc.Columns.Add("curent_star", typeof(int));
                        dtc.Columns.Add("RankTotal", typeof(int));
                        dtc.Columns.Add("RankThismonth", typeof(int)); 
                         
                        dtc.Rows.Add(new Object[] { 0, 0, 0, 0});

                        var c = GetJson(dtc);
                        var d = GetJson(dttop10);

                        String bothJson = "[" + c + "," + d + "]"; //Put both objects in an array of 2 elements
                        context.Response.Write(bothJson);
                        return;
                    }

                    break;

                case "getrankingall":

                    //if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false)
                    //{
                    //    return;
                    //}
                    if (!string.IsNullOrEmpty(context.Request.Params["orderby"]))
                    {
                        string orderby = context.Request.Params["orderby"];
                        string leagueId = context.Request.Params["leagueId"];
                        context.Response.Write(IFSController.member.GetMemberRanking(orderby, leagueId));
                    }
                    
                    //var viewby = 0;

                    //if (!string.IsNullOrEmpty(context.Request.Params["viewby"]))
                    //{
                    //    viewby = Convert.ToInt32(context.Request.Params["viewby"]);
                    //}

                    //DataTable dtr = new DataTable();

                    //dtr = getrankingall(viewby);

                    //if (dtr != null || dtr.Rows.Count > 0)
                    //{
                    //    context.Response.Write(GetJson(dtr)); 
                    //    return;
                    //} 

                    break;

                case "chkplaylist":

                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false)
                    {
                        return;
                    }

                    DataTable dtgpl = game.getplaylist(0);

                    if (dtgpl != null)
                    {
                        context.Response.Write(GetJson(dtgpl));
                        return;
                    }
                     
                    break;

                case "getsumaryallperleague":

                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false && string.IsNullOrEmpty(System.Web.HttpContext.Current.Session["curentUser"].ToString()))
                    {
                        return;
                    }
                    context.Response.Write(member.getMemberSumaryPerLeague());
                    context.Response.End();
                    break;
                    //DataTable dtspl = new DataTable();
                    //DataTable dtrankperleague = new DataTable();

                    //dtspl = member.getsumaryallperleague();
                    //dttop10 = member.gettop10latestperleague();
                    //dtrankperleague = member.getRanksumaryallperleagueRank();

                    //if (dtspl.Rows.Count > 0)
                    //{
                    //    //context.Response.Write(GetJson(dtgetsumaryall));
                    //    var c = GetJson(dtspl);
                    //    var d = GetJson(dttop10);
                    //    var e = GetJson(dtrankperleague);

                    //    String bothJson = "[" + c + "," + d + "," + e + "]"; //Put both objects in an array of 2 elements
                    //    context.Response.Write(bothJson);
                        
                    //    return;
                    //}

                    //break;

                case "getdataallmember":

                    dt = getdata();

                    if (dt.Rows.Count > 0)
                    {
                        context.Response.Write(GetJson(dt));
                        //var processes = System.Diagnostics.Process.GetProcesses();
                        //context.Response.Write(serializer.Serialize(processes.Select(p => p.ProcessName)));

                    }
                    break;

                case "sendpassword":

                    EmailManager empass = new EmailManager();
                    string SubjectPass = "ifunsoccer send password";


                    //HttpContext.Current.Request.UserHostAddress;  
                    //HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    //To get the IP address of the machine and not the proxy use the following code 
                    //HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();

                    try
                    { 
                        dt = member.sendpassword(context.Request.Params["sendemail"].ToString());

                        if (dt.Rows.Count == 1)
                        {
                            string strbodypass = "login name : " + dt.Rows[0]["email"].ToString() + " </br> password : " + dt.Rows[0]["password"].ToString();

                            empass.SendMail(context.Request.Params["sendemail"], SubjectPass, strbodypass, "noreply@ifunsoccer.com");

                            var wrapper = new { result = true, msg = "username and password has been sent to your email" };
                            context.Response.Write(serializer.Serialize(wrapper));
                            return;
                        }
                        else
                        {
                            var wrapper = new { result = false, msg = "unknow email address" };
                            context.Response.Write(serializer.Serialize(wrapper));
                            return;

                        }
                    }
                    catch (Exception ex)
                    {
                        var wrapper = new { result = false, msg = ex.Message.ToString() };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;

                    }

                case "confirmregister":


                    if (string.IsNullOrEmpty(context.Request.Params["memid"]))
                    {
                        var wrapper = new { result = "false", msg = "no memid" };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }

                    memid = EncryptAndDecrypt.Decrypt(context.Request.Params["memid"].ToString());

                    dt = null;

                    dt = member.chkconfirmregister(memid);

                    if (dt.Rows.Count > 0)
                    {
                        try
                        {
                            string strSqlConfirm = @"UPDATE  [dbo].[Members]
                                                   SET  [Active] =  @Active
                                                 WHERE  MemID = @MemID";

                            SqlCommand cmdf = new SqlCommand(strSqlConfirm, Conn);

                            cmdf.Parameters.AddWithValue("@Active", 1);
                            cmdf.Parameters.AddWithValue("@MemID", memid);

                            Conn.Open();

                            cmdf.ExecuteNonQuery();

                            if (Conn.State == ConnectionState.Open)
                                Conn.Close();

                            var wrapper = new { result = "true", msg = "confirmed register was completed" };
                            context.Response.Write(serializer.Serialize(wrapper));

                            return;
                        }
                        catch (Exception ex)
                        {
                            if (Conn.State == ConnectionState.Open)
                                Conn.Close();

                            var wrapper = new { result = "false", msg = ex.Message.ToString() };
                            context.Response.Write(serializer.Serialize(wrapper));

                            return;
                        }
                        finally
                        {
                            if (Conn.State == ConnectionState.Open)
                                Conn.Close();
                        }

                    }
                    //else 
                    //{
                    //    var wrapper = new { result = "false", msg = "no memid" };
                    //    context.Response.Write(serializer.Serialize(wrapper)); 
                    //    return; 
                    //}   

                    break;

                case "checkduplicateuser":



                    dt = member.chkdubplicate("username", context.Request.Params["UserName"]);

                    if (dt.Rows.Count > 0)
                        context.Response.Write(serializer.Serialize(string.Format("{0}", "username :" + context.Request.Params["UserName"] + " มีอยู่แล้ว กรูณาเปลี่ยน ใหม่ ")));


                    break;

                case "checkduplicateemail":


                    dt = member.chkdubplicate("email", context.Request.Params["email"]);

                    if (dt.Rows.Count > 0)
                    {
                        context.Response.Write(serializer.Serialize(string.Format("{0}", "email :" + context.Request.Params["email"] + " มีอยู่แล้ว กรูณาเปลี่ยน ใหม่ ")));
                    }

                    break;

                case "checkduplicatefirstname":


                    dt = member.chkdubplicate("firstname", context.Request.Params["firstname"]);

                    if (dt.Rows.Count > 0)
                    {
                        context.Response.Write(serializer.Serialize(string.Format("{0}", "first name :" + context.Request.Params["firstname"] + " มีอยู่แล้ว กรูณาเปลี่ยน ใหม่ ")));
                    }

                    break;

                case "savecontactus":

                    bool retcon = false;


                    retcon = savecontactus((string.IsNullOrEmpty(context.Request.Params["Topic"]) ? "" : context.Request.Params["Topic"]),
                                              (string.IsNullOrEmpty(context.Request.Params["FirstName"]) ? "" : context.Request.Params["FirstName"]),
                                              (string.IsNullOrEmpty(context.Request.Params["LastName"]) ? "" : context.Request.Params["LastName"]),
                                              (string.IsNullOrEmpty(context.Request.Params["tell"]) ? "" : context.Request.Params["tell"]),
                                              (string.IsNullOrEmpty(context.Request.Params["Email"]) ? "" : context.Request.Params["Email"]),
                                              (string.IsNullOrEmpty(context.Request.Params["msg"]) ? "" : context.Request.Params["msg"]), "0",
                                              (string.IsNullOrEmpty(context.Request.Params["type"]) ? 0 : Convert.ToInt16(context.Request.Params["type"])));

                    if (retcon)
                    {

                        try
                        {
                            if (Convert.ToInt16(context.Request.Params["type"]).Equals(1))
                            {
                                string strbody = "FirstName : " + (string.IsNullOrEmpty(context.Request.Params["FirstName"]) ? "" : context.Request.Params["FirstName"]) + "</br>";
                                strbody += "LastName : " + (string.IsNullOrEmpty(context.Request.Params["LastName"]) ? "" : context.Request.Params["LastName"]) + "</br>";
                                strbody += "Tell : " + (string.IsNullOrEmpty(context.Request.Params["tell"]) ? "" : context.Request.Params["tell"]) + "</br>";
                                strbody += "Email : " + (string.IsNullOrEmpty(context.Request.Params["Email"]) ? "no key" : context.Request.Params["Email"]) + "</br>";
                                strbody += "Message : " + (string.IsNullOrEmpty(context.Request.Params["msg"]) ? "" : context.Request.Params["msg"]) + "";

                                List<string> list = new List<string>();
                                list.Add("admin@ifunsoccer.com");
                                list.Add("asawintu@hotmail.com");
                                list.Add("ifunsoccer@gmail.com");
                                list.Add("redharing_555@hotmail.com");

                                em.SendMail(list, (string.IsNullOrEmpty(context.Request.Params["Topic"]) ? "" : context.Request.Params["Topic"]),
                                                   strbody, "admin@ifunsoccer.com");
                            }

                            #region easy email
                            //========================================================================
                            //MailMessage message = new MailMessage();

                            //message.To.Add(new MailAddress("ifunsoccer@gmail.com"));
                            //message.To.Add(new MailAddress("asawintun@hotmail.com"));
                            //message.CC.Add(new MailAddress("admin@ifunsoccer.com"));
                            //message.CC.Add(new MailAddress("redharing_555@hotmail.com"));

                            //message.From = new MailAddress((string.IsNullOrEmpty(context.Request.Params["Email"]) ? "nokeyemail@ifunsoccer.com" : context.Request.Params["Email"]));
                            //message.Subject = (string.IsNullOrEmpty(context.Request.Params["Topic"]) ? "" : context.Request.Params["Topic"]);
                            //message.Body = strbody;
                            //message.IsBodyHtml = true;
                            //message.BodyEncoding = System.Text.Encoding.UTF8;
                            //message.SubjectEncoding = System.Text.Encoding.UTF8;

                            //SmtpClient client = new SmtpClient();
                            //client.Port = 25; // Gmail works on this port
                            //client.Host = "mail.ifunsoccer.com";
                            //System.Net.NetworkCredential nc = new System.Net.NetworkCredential("admin@ifunsoccer.com", "Ifspa55w0rd@9");// is u are using Gmail
                            //client.EnableSsl = true;
                            //client.UseDefaultCredentials = false;
                            //client.Credentials = nc;
                            //client.Send(message);
                            //========================================================================

                            //MailMessage message = new MailMessage();

                            //message.To.Add(new MailAddress("ifunsoccer@gmail.com"));
                            //message.To.Add(new MailAddress("asawintun@hotmail.com"));
                            //message.CC.Add(new MailAddress("asawintun@gmail.com"));
                            //message.CC.Add(new MailAddress("redharing_555@hotmail.com"));

                            //message.From = new MailAddress((string.IsNullOrEmpty(context.Request.Params["Email"]) ? "nokeyemail@ifunsoccer.com" : context.Request.Params["Email"]));
                            //message.Subject = (string.IsNullOrEmpty(context.Request.Params["Topic"]) ? "" : context.Request.Params["Topic"]);
                            //message.Body = strbody;
                            //message.IsBodyHtml = true;
                            //message.BodyEncoding = System.Text.Encoding.UTF8;
                            //message.SubjectEncoding = System.Text.Encoding.UTF8;

                            //SmtpClient client = new SmtpClient();
                            //client.Port = 587; // Gmail works on this port
                            //client.Host = "smtp.gmail.com";
                            //System.Net.NetworkCredential nc = new System.Net.NetworkCredential("ifunsoccer@gmail.com", "pa55w0rd@9");// is u are using Gmail
                            //client.EnableSsl = true;
                            //client.UseDefaultCredentials = false;
                            //client.Credentials = nc;
                            //client.Send(message);
                            #endregion


                        }
                        catch (Exception ex)
                        {
                            if (Conn.State == ConnectionState.Open)
                                Conn.Close();

                            var wrapper = new { result = "true", msg = ex.Message.ToString() };
                            context.Response.Write(serializer.Serialize(wrapper));
                            return;

                        }

                        var wrapper1 = new { result = "true", msg = "ส่งข้อความเรียบร้อย ขอบคุณครับ" };
                        context.Response.Write(serializer.Serialize(wrapper1));
                        return;
                    }
                    else
                    {
                        var wrapper = new { result = "false", msg = "error " };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }

                    break;



                case "saveregister":
                    //context.Response.Write(serializer.Serialize(string.Format("data: {0}\n\n", new Random().Next(1, 100))));

                    Int64 ID = 0;
                    string strSql = "";


                    dt = member.chkdubplicate("username", context.Request.Params["username"]);
                    if (dt.Rows.Count > 0)
                    {

                        var wrapper = new { result = "false", msg = "username  :" + context.Request.Params["username"] + " มีอยู่แล้ว กรูณาเปลี่ยน ใหม่ " };
                        context.Response.Write(serializer.Serialize(wrapper));

                        return;
                    }
                    //===============

                    dt = null;
                    dt = member.chkdubplicate("email", context.Request.Params["email"]);
                    if (dt.Rows.Count > 0)
                    {
                        var wrapper = new { result = false, msg = "email  :" + context.Request.Params["email"] + " มีอยู่แล้ว กรูณาเปลี่ยน ใหม่ " };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }

                    //===============
                    dt = null;
                    dt = member.chkdubplicate("firstname", context.Request.Params["firstname"]);
                    if (dt.Rows.Count > 0)
                    {
                        var wrapper = new { result = false, msg = "first name  :" + context.Request.Params["firstname"] + " มีอยู่แล้ว กรูณาเปลี่ยน ใหม่ " };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }


                    try
                    {

                        string clientIp = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim();

                        strSql = @"INSERT INTO  [dbo].[Members]
                                        ([UserName] ,[FirstName] ,[LastName] ,[Password] ,[Telephone] ,[Sex] ,[Email] ,[Birthdate] ,[City] ,[Active] ,[ProfileImage],[Ipaddress],Curent_Point,Curent_Star)
                                    VALUES
                                        (@UserName,  @FirstName, @LastName, @Password, @Telephone, @Sex, @Email, @Birthdate, @City,  @Active, @ProfileImage,@Ipaddress,@Curent_Point,@Curent_Star);Select Scope_Identity()";


                        SqlCommand cmd = new SqlCommand(strSql, Conn);

                        cmd.Parameters.AddWithValue("@UserName", (string.IsNullOrEmpty(context.Request.Params["username"]) ? "" : context.Request.Params["username"]));
                        cmd.Parameters.AddWithValue("@FirstName", (string.IsNullOrEmpty(context.Request.Params["firstname"]) ? "" : context.Request.Params["firstname"]));
                        cmd.Parameters.AddWithValue("@LastName", (string.IsNullOrEmpty(context.Request.Params["lastname"]) ? "" : context.Request.Params["lastname"]));
                        cmd.Parameters.AddWithValue("@Password", (string.IsNullOrEmpty(context.Request.Params["password"]) ? "" : context.Request.Params["password"]));
                        cmd.Parameters.AddWithValue("@Telephone", (string.IsNullOrEmpty(context.Request.Params["telephone"]) ? "" : context.Request.Params["telephone"]));
                        cmd.Parameters.AddWithValue("@Sex", Convert.ToInt16((context.Request.Params["sex"]) == "m" ? 1 : 0));
                        cmd.Parameters.AddWithValue("@Email", (string.IsNullOrEmpty(context.Request.Params["email"]) ? "" : context.Request.Params["email"]));
                        cmd.Parameters.AddWithValue("@Birthdate", DateTime.Now);
                        cmd.Parameters.AddWithValue("@City", 1);
                        cmd.Parameters.AddWithValue("@Active", 1);
                        cmd.Parameters.AddWithValue("@ProfileImage", "1");
                        cmd.Parameters.AddWithValue("@Ipaddress", clientIp);
                        cmd.Parameters.AddWithValue("@Curent_Point", 0);
                        cmd.Parameters.AddWithValue("@Curent_Star", 10);

                        Conn.Open();

                        ID = Convert.ToInt32(cmd.ExecuteScalar());


                        if (ID > 0)
                        {

                            strSql = @"UPDATE [dbo].[Members]
                                   SET [ProfileImage] =  @ProfileImage
                                 WHERE  MemID = @MemID";

                            SqlCommand cmde = new SqlCommand(strSql, Conn);

                            cmde.Parameters.AddWithValue("@ProfileImage", ID);
                            cmde.Parameters.AddWithValue("@MemID", ID);

                            cmde.ExecuteNonQuery();
                        }

                    }
                    catch (Exception ex)
                    {
                        if (Conn.State == ConnectionState.Open)
                            Conn.Close();

                        var wrapper = new { result = false, msg = ex.Message.ToString() };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }
                    finally
                    {
                        Conn.Close();
                    }

                    if (ID > 0)
                    {

                        var wrapper = new { result = true, msg = "register เรียบร้อย" };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }


                    break;

                case "saveregisterold":
                    //context.Response.Write(serializer.Serialize(string.Format("data: {0}\n\n", new Random().Next(1, 100))));

                    //Int64 ID2 = 0;
                    //string strSql2 = "";


                    //dt = chkdubplicate("username", context.Request.Params["username"]);
                    //if (dt.Rows.Count > 0)
                    //{

                    //    var wrapper = new { result = "false", msg = "username  :" + context.Request.Params["username"] + " มีอยู่แล้ว กรูณาเปลี่ยน ใหม่ " };
                    //    context.Response.Write(serializer.Serialize(wrapper));

                    //    return;
                    //}
                    ////===============

                    //dt = null;
                    //dt = chkdubplicate("email", context.Request.Params["email"]);
                    //if (dt.Rows.Count > 0)
                    //{
                    //    var wrapper = new { result = false, msg = "email  :" + context.Request.Params["email"] + " มีอยู่แล้ว กรูณาเปลี่ยน ใหม่ " };
                    //    context.Response.Write(serializer.Serialize(wrapper));
                    //    return;
                    //}

                    ////===============
                    //dt = null;
                    //dt = chkdubplicate("firstname", context.Request.Params["firstname"]);
                    //if (dt.Rows.Count > 0)
                    //{
                    //    var wrapper = new { result = false, msg = "first name  :" + context.Request.Params["firstname"] + " มีอยู่แล้ว กรูณาเปลี่ยน ใหม่ " };
                    //    context.Response.Write(serializer.Serialize(wrapper));
                    //    return;
                    //}


                    //try
                    //{

                    //    //HttpContext.Current.Request.UserHostAddress;  
                    //    //HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    //    //To get the IP address of the machine and not the proxy use the following code 
                    //    // HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString ();

                    //    string clientIp = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim();

                    //    strSql = @"INSERT INTO [ifunsoccer].[dbo].[Members]
                    //                    ([UserName] ,[FirstName] ,[LastName] ,[Password] ,[Telephone] ,[Sex] ,[Email] ,[Birthdate] ,[City] ,[Active] ,[ProfileImage],[Ipaddress])
                    //                VALUES
                    //                    (@UserName,  @FirstName, @LastName, @Password, @Telephone, @Sex, @Email, @Birthdate, @City,  @Active, @ProfileImage,@Ipaddress);Select Scope_Identity()";


                    //    SqlCommand cmd = new SqlCommand(strSql, Conn);

                    //    cmd.Parameters.AddWithValue("@UserName", (string.IsNullOrEmpty(context.Request.Params["username"]) ? "" : context.Request.Params["username"]));
                    //    cmd.Parameters.AddWithValue("@FirstName", (string.IsNullOrEmpty(context.Request.Params["firstname"]) ? "" : context.Request.Params["firstname"]));
                    //    cmd.Parameters.AddWithValue("@LastName", (string.IsNullOrEmpty(context.Request.Params["lastname"]) ? "" : context.Request.Params["lastname"]));
                    //    cmd.Parameters.AddWithValue("@Password", (string.IsNullOrEmpty(context.Request.Params["password"]) ? "" : context.Request.Params["password"]));
                    //    cmd.Parameters.AddWithValue("@Telephone", (string.IsNullOrEmpty(context.Request.Params["telephone"]) ? "" : context.Request.Params["telephone"]));
                    //    cmd.Parameters.AddWithValue("@Sex", Convert.ToInt16((context.Request.Params["sex"]) == "m" ? 1 : 0));
                    //    cmd.Parameters.AddWithValue("@Email", (string.IsNullOrEmpty(context.Request.Params["email"]) ? "" : context.Request.Params["email"]));
                    //    cmd.Parameters.AddWithValue("@Birthdate", DateTime.Now);
                    //    cmd.Parameters.AddWithValue("@City", 1);
                    //    cmd.Parameters.AddWithValue("@Active", 0);
                    //    cmd.Parameters.AddWithValue("@ProfileImage", "1");
                    //    cmd.Parameters.AddWithValue("@Ipaddress", clientIp);

                    //    Conn.Open();

                    //    ID = Convert.ToInt32(cmd.ExecuteScalar());


                    //    if (ID > 0)
                    //    {

                    //        strSql = @"UPDATE [ifunsoccer].[dbo].[Members]
                    //               SET [ProfileImage] =  @ProfileImage
                    //             WHERE  MemID = @MemID";

                    //        SqlCommand cmde = new SqlCommand(strSql, Conn);

                    //        cmde.Parameters.AddWithValue("@ProfileImage", ID);
                    //        cmde.Parameters.AddWithValue("@MemID", ID);

                    //        cmde.ExecuteNonQuery();

                    //        Subject = "confirmation email register from ifunsoccer ";

                    //        string Linkstr = HttpContext.Current.Request.Url.AbsoluteUri.ToLower().Replace("ssehandler.ashx", "registerconfirm.html") + "?memid=" +
                    //                          EncryptAndDecrypt.Encrypt(ID.ToString()) + "&confirmemail=" + EncryptAndDecrypt.Encrypt("yes");


                    //        Linkstr = Regex.Replace(Linkstr, "<br>|<br />|<br/>", "\n");
                    //        //Linkstr = Regex.Replace(Linkstr, @"([\s])(www\..*?|http://.*?)([\s])", "$1<a href=\"$2\" target=\"_blank\">$2</a>$3");
                    //        //Linkstr = Regex.Replace(Linkstr, @"href=""www\.", "href=\"http://www.");
                    //        Linkstr = Linkstr.Trim();


                    //        //message.Body = @"<a href="http://yoursite.com/unsubscribe.aspx?id=userId&token={some-guid-value-stored-in-your-db} > Click here to unsubscribe </a>";


                    //        try
                    //        {
                    //            string strbody = "confirmation email register from ifunsoccer </br>  please click link to confirm email </br> " + Linkstr;

                    //            // string strbody = "confirmation email register from ifunsoccer </br> please click link to confirm email </br>  " + Linkstr ;

                    //            em.SendMail(context.Request.Params["email"].ToString(), Subject, strbody, "noreply@ifunsoccer.com"); // Send email to employee
                    //        }
                    //        catch (Exception ex)
                    //        {
                    //            if (Conn.State == ConnectionState.Open)
                    //                Conn.Close();

                    //            var wrapper = new { result = false, msg = ex.Message.ToString() };
                    //            context.Response.Write(serializer.Serialize(wrapper));
                    //            return;

                    //        }
                    //    }

                    //}
                    //catch (Exception ex)
                    //{
                    //    if (Conn.State == ConnectionState.Open)
                    //        Conn.Close();
                    //}
                    //finally
                    //{
                    //    Conn.Close();
                    //}

                    //if (ID > 0)
                    //{

                    //    var wrapper = new { result = true, msg = "register เรียบร้อย ขอบคุณ  " };
                    //    context.Response.Write(serializer.Serialize(wrapper));
                    //    return;
                    //}

                    break;


                case "editmemberr":

                    if (string.IsNullOrEmpty(context.Request.Params["memid"]))
                    {
                        var wrapper = new { result = "false", msg = "no memid" };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }

                    memid = EncryptAndDecrypt.Decrypt(context.Request.Params["memid"].ToString());

                    dt = member.chkdubplicate("memid", memid);

                    if (dt.Rows.Count > 0)
                    {
                        try
                        {
                            string strSqlConfirm = @"UPDATE [dbo].[Members]
                                   SET  [Active] =  @Active
                                 WHERE  MemID = @MemID";

                            SqlCommand cmde = new SqlCommand(strSqlConfirm, Conn);

                            cmde.Parameters.AddWithValue("@Active", 1);
                            cmde.Parameters.AddWithValue("@MemID", memid);

                            Conn.Open();

                            cmde.ExecuteNonQuery();

                            var wrapper = new { result = "true", msg = "confirmed register was completed" };
                            context.Response.Write(serializer.Serialize(wrapper));

                            return;
                        }
                        catch (Exception ex)
                        {

                            if (Conn.State == ConnectionState.Open)
                                Conn.Close();


                            var wrapper = new { result = "false", msg = ex.Message.ToString() };
                            context.Response.Write(serializer.Serialize(wrapper));

                            return;

                        }

                    }

                    break;

                case "GreetMe2":

                    HttpResponse Response = context.Response;
                    DateTime startDate = DateTime.Now;
                    Response.ContentType = "text/event-stream";
                    while (startDate.AddMinutes(1) > DateTime.Now)
                    {
                        Response.Write(string.Format("data: {0}\n\n", new Random().Next(1, 100)));
                        Response.Flush();
                        System.Threading.Thread.Sleep(5000);
                    }
                    Response.Close();

                    break;

                case "login":

                    DataTable dtlogin = new DataTable();

                    if (!string.IsNullOrEmpty(context.Request.Params["email"]) && !string.IsNullOrEmpty(context.Request.Params["password"]))
                    {

                        try
                        {

                            bool chk = member.login(context.Request.Params["email"], context.Request.Params["password"]);

                            if (chk)
                            {
                                member.SetAuthenUser(context.Request.Params["email"].ToString());

                                var wrapper = new { result = true, msg = "ok" };
                                context.Response.Write(serializer.Serialize(wrapper));
                                return;
                            }
                            else
                            {
                                var wrapper = new { result = false, msg = "no user" };
                                context.Response.Write(serializer.Serialize(wrapper));
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            var wrapper = new { result = false, msg = ex.Message.ToString() };
                            context.Response.Write(serializer.Serialize(wrapper));
                            return;
                        }

                    }
                    else
                    {
                        var wrapper = new { result = false, msg = "error" };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }

                    break;


                case "chklogin":

                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        var wrapper = new { result = true, msg = "completed" };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }
                    else
                    {
                        var wrapper = new { result = false, msg = "" };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }

                    break;

                case "logout":

                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        System.Web.Security.FormsAuthentication.SignOut();

                        var wrapper = new { result = true, msg = "completed" };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }
                    else
                    {
                        var wrapper = new { result = false, msg = "no" };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }


                    break;

                case "getprofile":

                    DataTable dtp = new DataTable();

                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        dtp = member.getprofile(System.Web.HttpContext.Current.User.Identity.Name.ToString());

                        context.Response.Write(GetJson(dtp));
                        return;
                    }
                    else if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Session["curentUser"].ToString()))
                    {
                        dtp = member.getprofile(HttpContext.Current.Session["curentUser"].ToString());
                        context.Response.Write(GetJson(dtp));
                    }

                    break;


                case "savegame":


                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false && string.IsNullOrEmpty(System.Web.HttpContext.Current.Session["curentUser"].ToString()))
                    {
                        var wrapper = new { result = "true", msg = "not login" };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }


                    bool ret = false;

                    ret = savegame(context.Request.Params["leagueid"].ToString(),
                                  (Convert.ToInt64(context.Request.Params["matchid"].ToString())),
                                  ((context.Request.Params["selectteam"].ToString())),
                                  (Convert.ToInt64(context.Request.Params["selectteamid"].ToString())),
                                  (Convert.ToDouble(context.Request.Params["starbet"].ToString())),
                                  (Convert.ToDouble(context.Request.Params["Current_PriceHandicap"].ToString())),
                                  context.Request.Params["Current_TeamHandicap"].ToString());

                    //ret = savegame((string.IsNullOrEmpty(context.Request.Params["memid"]) ? 0 : Convert.ToInt64(context.Request.Params["memid"])),
                    //                (string.IsNullOrEmpty(context.Request.Params["leagueid"]) ? 0 : Convert.ToInt64(context.Request.Params["leagueid"])),
                    //                (string.IsNullOrEmpty(context.Request.Params["matchid"]) ? 0 : Convert.ToInt64(context.Request.Params["matchid"])),
                    //                (string.IsNullOrEmpty(context.Request.Params["selectteam"]) ? "" : (context.Request.Params["selectteam"])),
                    //                (string.IsNullOrEmpty(context.Request.Params["selectteamid"]) ? 0 : Convert.ToInt64(context.Request.Params["selectteamid"])),
                    //                (string.IsNullOrEmpty(context.Request.Params["starbet"]) ? 0 : Convert.ToDecimal(context.Request.Params["starbet"])),
                    //                (string.IsNullOrEmpty(context.Request.Params["Current_PriceHandicap"]) ? 0 : Convert.ToDecimal(context.Request.Params["Current_TeamHandicap"])),
                    //                context.Request.Params["Current_TeamHandicap"]);

                    //(string.IsNullOrEmpty(context.Request.Params["Current_TeamHandicap"]) ? " " : Convert.ToString(context.Request.Params["Current_TeamHandicap"])));


                    if (ret)
                    { 
                        var wrapper = new { result = "true", msg = "completed" };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }
                    else
                    {
                        var wrapper = new { result = "false", msg = "error " };
                        context.Response.Write(serializer.Serialize(wrapper));
                        return;
                    }

                    break;

                 
                case "getdataprocess":

                    var processes = System.Diagnostics.Process.GetProcesses();
                    context.Response.Write(serializer.Serialize(processes.Select(p => p.ProcessName)));
                    break;
                case "addpoint":

                    const int shareAdd = 4;
                    string result;
                    member.AddStar(shareAdd, 5, out result);//TypeID 5 is star from share facebook
                    context.Response.Write(result);
                      context.Response.ContentType = "text/plain";
                    context.Response.End();
                    break;
                case "getnotify":
                    context.Response.ContentType = "text/plain";
                        var notify = member.getNotify();

                        context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(notify));
                    
                    
                    context.Response.End();
                    
                    break;
                case "updatenotify":
                    var notifyID = context.Request.Params["notifyid"];
                    context.Response.Write(member.UpdateNoti(notifyID));
                    context.Response.ContentType = "text/plain";
                    context.Response.End();
                    
                    break;
                    case "getleague":
                    string leagueType = context.Request.Params["leagueType"];
                    var league = score.GetLeague(leagueType);
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(league);
                        context.Response.End();
                        break;
                case "authenticate":
                    if (string.IsNullOrEmpty(context.Request["urlAuthen"]))
                    {
                        context.Response.Write(false);
                    }
                    else
                    {
                        context.Response.Write(System.Web.HttpContext.Current.Request.IsAuthenticated);
                    }
                    context.Response.ContentType = "text/plain";
                    context.Response.End();
                    break;
                case "fblogin":
                    var fblogin = context.Request["username"];
                    var accessToken = context.Request["accesstoken"];
                    var url = context.Request["urlAuthen"];
                    if (string.IsNullOrEmpty(fblogin) || string.IsNullOrEmpty(accessToken))
                    {
                        
                        if (string.IsNullOrEmpty(url))
                        {
                            context.Response.Write(false);
                        }
                        else
                        {
                            context.Response.Write(security.needAuthen(url));
                        }

                    }
                    else
                    {
                        var m = member.GetMember(fblogin);
                        if (m.Count() > 0)
                        {
                            context.Response.Write(member.SetAuthenUserFB(fblogin, accessToken));
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(url))
                            {
                                context.Response.Write(false);
                            }
                            else
                            {
                                context.Response.Write(security.needAuthen(url));
                            }
                        }
                    }

                    context.Response.ContentType = "text/plain";
                    context.Response.End();
                    break;
                //default:
                //    var processes = System.Diagnostics.Process.GetProcesses();
                //    context.Response.Write(serializer.Serialize(processes.Select(p => p.ProcessName)));
                //    break;

            }

        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public class GetClolumn
        {
            public string UserName { get; set; }
            public string FirstName { get; set; }
        }


        #region ==============Game=================

        private string Left(string inString, int inInt)
        {
            if (inInt > inString.Length)
                inInt = inString.Length;
            return inString.Substring(0, inInt);
        }
        private string Right(string str, int length)
        {
            return str.Substring(str.Length - length, length);
        }

        private bool savegametrans(long MemID, long RefID, Int32 TypeID, double Mpt_Cal_Point, double Mpt_Cal_Star)
        {
            SqlConnection Conn = new SqlConnection(getConn());
            SqlDataAdapter adapter = new SqlDataAdapter();


            try
            {

                string strSql = @"INSERT INTO  [dbo].[Members_point_tran]
                                        ([MemID],RefID,TypeID,Mpt_Cal_Point,Mpt_Cal_Star)
                                    VALUES
                                        (@MemID, @RefID, @TypeID, @Mpt_Cal_Point, @Mpt_Cal_Star)";


                SqlCommand cmd = new SqlCommand(strSql, Conn);

                cmd.Parameters.AddWithValue("@MemID", MemID);
                cmd.Parameters.AddWithValue("@RefID", RefID);
                cmd.Parameters.AddWithValue("@TypeID", TypeID);
                cmd.Parameters.AddWithValue("@Mpt_Cal_Point", Mpt_Cal_Point);
                cmd.Parameters.AddWithValue("@Mpt_Cal_Star", Mpt_Cal_Star);

                Conn.Open();

                cmd.ExecuteScalar();

            }
            catch (Exception ex)
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();

                return false;
            }
            finally
            {
                Conn.Close();
            }

            return true;

        }

        private bool savegame(string LeagueID, long MatchID, string Selectteam, long SelectteamID, double StarBet, double Current_PriceHandicap, string Current_TeamHandicap)
        {
            SqlConnection Conn = new SqlConnection(getConn());
            SqlDataAdapter adapter = new SqlDataAdapter();

            string username = System.Web.HttpContext.Current.User.Identity.Name.ToString();
            if(string.IsNullOrEmpty(username)){
                 username = System.Web.HttpContext.Current.Session["curentUser"].ToString();
            }
            DataTable dtmid = member.getprofile(username);
            long Memid = Convert.ToInt64(dtmid.Rows[0]["memid"]);

            if (checkgameplayed(Memid, MatchID) >= 1)
            {
                return false;
            }

            if (Convert.ToDateTime(dtgetmatchbymatchID(MatchID).Rows[0]["matchtime"]) < DateTime.Now) { return false; }

            if (StarBet > Convert.ToDouble(dtmid.Rows[0]["curent_star"])) { return false;}


            try
            {
                string clientIp = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim();

                string strSql = @"INSERT INTO  [dbo].[Members_play]
                                        ([MemID] ,[LeagueID] ,[MatchID] ,[Selectteam],[SelectteamID] ,[StarBet] ,[Status] ,
                                        [Ipaddress],ScoreA,ScoreB,Current_PriceHandicap,Current_TeamHandicap)
                                    VALUES
                                        (@MemID,@LeagueID, @MatchID, @Selectteam, @SelectteamID, @StarBet, @Status, 
                                         @Ipaddress,@ScoreA,@ScoreB,@Current_PriceHandicap,@Current_TeamHandicap);Select Scope_Identity()";



                SqlCommand cmd = new SqlCommand(strSql, Conn);

                cmd.Parameters.AddWithValue("@MemID", dtmid.Rows[0]["memid"]);
                cmd.Parameters.AddWithValue("@LeagueID", LeagueID);
                cmd.Parameters.AddWithValue("@MatchID", MatchID);
                cmd.Parameters.AddWithValue("@Selectteam", Selectteam);
                cmd.Parameters.AddWithValue("@SelectteamID", SelectteamID);
                cmd.Parameters.AddWithValue("@StarBet", StarBet);
                cmd.Parameters.AddWithValue("@Status", 0);
                cmd.Parameters.AddWithValue("@Ipaddress", clientIp);
                cmd.Parameters.AddWithValue("@ScoreA", 0);
                cmd.Parameters.AddWithValue("@ScoreB", 0);
                cmd.Parameters.AddWithValue("@Current_PriceHandicap", Current_PriceHandicap);
                cmd.Parameters.AddWithValue("@Current_TeamHandicap", Current_TeamHandicap);

                Conn.Open();

                long ID = Convert.ToInt32(cmd.ExecuteScalar());

                if (ID > 0)
                {
                    savegametrans(Convert.ToInt64(dtmid.Rows[0]["memid"]), ID, 1, Convert.ToDouble(dtmid.Rows[0]["curent_point"]), Convert.ToDouble(dtmid.Rows[0]["curent_star"]));

                    updategamepoint(Memid, StarBet);
                }

            }
            catch (Exception ex)
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();

                return false;
            }
            finally
            {
                Conn.Close();
            }

            return true;

        }

        private bool updategamepoint(long MemID, double StarBet)
        {
            SqlConnection Conn = new SqlConnection(getConn());
            SqlDataAdapter adapter = new SqlDataAdapter();

            try
            {

                string strSql = @"UPDATE [dbo].[Members]
                                   SET Curent_Star = Curent_Star - @Curent_StarADD 
                                 WHERE  MemID = @MemID";

                SqlCommand cmd = new SqlCommand(strSql, Conn);

                cmd.Parameters.AddWithValue("@MemID", MemID);
                cmd.Parameters.AddWithValue("@Curent_StarADD", StarBet);

                Conn.Open();

                cmd.ExecuteNonQuery();

            }
            catch (Exception ex)
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();

                return false;
            }
            finally
            {
                Conn.Close();
            }

            return true;

        }

        private int checkgameplayed(long MemID, long MatchID)
        {
            SqlConnection Conn = new SqlConnection(getConn());
            SqlDataAdapter adapter = new SqlDataAdapter();

            int ret = 0;

            string query = "select 1 existed from Members_play where  MemID = @MemID and MatchID = @MatchID";

            adapter.SelectCommand = new SqlCommand(query, Conn);

            if ((MemID > 0))
            {
                adapter.SelectCommand.Parameters.AddWithValue("@MemID", MemID);
                adapter.SelectCommand.Parameters.AddWithValue("@MatchID", MatchID);
            }


            DataTable dt = new DataTable();

            Conn.Open();
            try
            {
                adapter.Fill(dt);
            }
            catch (Exception ex)
            {
                dt = null;
            }

            finally
            {
                Conn.Close();
            }

            if (dt.Rows.Count >= 1)
            {
                ret = 1;
            }

            return ret;

        }


        private DataTable dtgetmatchbymatchID(long MatchID)
        {
            SqlConnection Conn = new SqlConnection(getConn());
            SqlDataAdapter adapter = new SqlDataAdapter();

            int ret = 0;

            string query = "select matchtime from match where   ID = @MatchID ";

            adapter.SelectCommand = new SqlCommand(query, Conn);

            if ((MatchID > 0))
            {
                adapter.SelectCommand.Parameters.AddWithValue("@MatchID", MatchID); 
            }


            DataTable dt = new DataTable();

            Conn.Open();
            try
            {
                adapter.Fill(dt);
            }
            catch (Exception ex)
            {
                dt = null;
            } 
            finally
            {
                Conn.Close();
            }


            return dt;

        }

        //public int getresultpoint(long MemID, long MatchID, out decimal retpoint, out decimal retstar)
        //{
        //    decimal Current_PriceHandicap = 0;
        //    string[] Score;
        //    string Current_TeamHandicap = "";
        //    decimal Calresult = 0;
        //    decimal Current_StarBet = 0;
        //    string Current_Teamselected;
        //    decimal Calfinalpoint = 0;
        //    double EPSILON = 0.000001;
        //    string Current_PriceHandicapStr;

        //    DataTable dt = new DataTable();

        //    dt = game.getplaylist(1, DateTime.Now,0);


        //    if (dt.Rows.Count > 0)
        //    {

        //        Current_PriceHandicap = (decimal)dt.Rows[0]["Current_PriceHandicap"];

        //        if (Current_PriceHandicap.Equals(0))
        //        { }
        //        else
        //            Current_PriceHandicap = Current_PriceHandicap * -1;

        //        //===================================================================
        //        //if (Current_PriceHandicap > 1)
        //        //{
        //        //    Current_PriceHandicapStr = Convert.ToString(Current_PriceHandicap);
        //        //    Current_PriceHandicapStr = Right(Current_PriceHandicapStr, 2);
        //        //    Current_PriceHandicapStr = "0." + Current_PriceHandicapStr;
        //        //    Current_PriceHandicap = Convert.ToDecimal(Current_PriceHandicapStr);
        //        //}



        //        Current_TeamHandicap = (string)dt.Rows[0]["Current_TeamHandicap"];
        //        Current_Teamselected = (string)dt.Rows[0]["selectteam"];
        //        Score = dt.Rows[0]["score"].ToString().Split('-');
        //        Current_StarBet = (decimal)dt.Rows[0]["StarBet"];


        //        if (Current_TeamHandicap.ToString().ToLower().Equals(Current_Teamselected.ToString().ToLower())) // selected team ต่อ
        //        {
        //            Calresult = (Convert.ToInt32(Score[0]) - Convert.ToInt32(Score[1])) - Current_PriceHandicap;

        //            if (Calresult > 0)
        //            {
        //                if (Math.Abs((double)Calresult - (0.25)) < EPSILON)
        //                    Calfinalpoint = 1; // half point = 1
        //                else
        //                    Calfinalpoint = 2;
        //            }
        //            else if (Calresult.Equals(0))
        //                Calfinalpoint = 0; // tie = 0
        //            else if (Calresult < -0)
        //            {
        //                if (Math.Abs((double)Calresult - (-0.25)) < EPSILON)
        //                {
        //                    if (Calresult < -0)
        //                    {
        //                        Calfinalpoint = -1; // lose half point = 1  
        //                    }
        //                    else
        //                    {
        //                        Calfinalpoint = 1; // get half point = 1  
        //                    }
        //                }
        //                else
        //                    Calfinalpoint = -2;
        //            }
        //            else
        //                Calfinalpoint = 1; // half point = 1
        //        }
        //        else //=======================================// selected team รอง
        //        {
        //            Calresult = (Convert.ToInt32(Score[1]) - Convert.ToInt32(Score[0])) - Current_PriceHandicap;

        //            if (Calresult > 0)
        //            {
        //                if (Math.Abs((double)Calresult - (0.25)) < EPSILON)
        //                    Calfinalpoint = 1; // half point = 1
        //                else
        //                    Calfinalpoint = 2;
        //            }
        //            else if (Calresult.Equals(0))
        //            {
        //                if ((Current_PriceHandicap - (-2) >= 4))
        //                {
        //                    Calfinalpoint = 2;
        //                }
        //                else
        //                    Calfinalpoint = 0;
        //            }
        //            else if (Calresult < -0)
        //            {
        //                if (Math.Abs((double)Calresult - (-0.25)) < EPSILON)
        //                {
        //                    if (Calresult < -0)
        //                    {
        //                        Calfinalpoint = 1; // lose half point = 1  
        //                    }
        //                    else
        //                    {
        //                        Calfinalpoint = 1; // get half point = 1  
        //                    }
        //                }
        //                else if (Math.Abs((double)Calresult - (-0.50)) < EPSILON)
        //                {
        //                    Calfinalpoint = 2;
        //                }
        //                else if (Math.Abs((double)Calresult - (-0.75)) < EPSILON)
        //                {
        //                    Calfinalpoint = 2;
        //                }
        //                else if (Math.Abs((double)Calresult - (-1)) < EPSILON)
        //                {
        //                    Calfinalpoint = 2;
        //                }
        //                else if (Math.Abs((double)Calresult - (-1.25)) < EPSILON)
        //                {
        //                    Calfinalpoint = 2;
        //                }
        //                else if (Math.Abs((double)Calresult - (-1.50)) < EPSILON)
        //                {
        //                    Calfinalpoint = 2;
        //                }
        //                else if (Math.Abs((double)Calresult - (-1.75)) < EPSILON)
        //                {
        //                    Calfinalpoint = 2;
        //                }
        //                else if (Math.Abs((double)Calresult - (-2)) < EPSILON)
        //                {
        //                    //Calfinalpoint = 0;
        //                    Calfinalpoint = 2;
        //                }
        //                else if (Math.Abs((double)Calresult - (-2.25)) < EPSILON)
        //                {
        //                    Calfinalpoint = 1;
        //                }
        //                else if (Math.Abs((double)Calresult - (-2.50)) < EPSILON)
        //                {
        //                    Calfinalpoint = 2;
        //                }
        //                else if (Math.Abs((double)Calresult - (-2.75)) < EPSILON)
        //                {
        //                    Calfinalpoint = 2;
        //                }
        //                else if (Math.Abs((double)Calresult - (-3.75)) < EPSILON)
        //                {
        //                    Calfinalpoint = -1;
        //                }
        //                else if (Math.Abs((double)Calresult - (-4.25)) < EPSILON)
        //                {
        //                    Calfinalpoint = 1;
        //                }
        //                else
        //                    Calfinalpoint = -2;
        //            }
        //            else
        //                Calfinalpoint = 1; // half point = 1


        //        }

        //    }



        //    retpoint = Calfinalpoint;
        //    retstar = Calfinalpoint;

        //    return 1;

        //}


        public class calpointstar
        {
            public long point { get; set; }
            public decimal star { get; set; }
        }
        #endregion

    }


    public class EncryptAndDecrypt
    {

        public static string Encrypt(string stringToEncrypt)
        {
            FormsAuthenticationTicket tk = new FormsAuthenticationTicket(stringToEncrypt, false, 1440); // minute 60 = 1 hrs 
            return FormsAuthentication.Encrypt(tk);
        }

        public static string Decrypt(string encryptedString)
        {
            FormsAuthenticationTicket tk = FormsAuthentication.Decrypt(encryptedString);
            return tk.Name;
        }
    }
    public class EmailManager
    {

        #region MailSettings
        private string _SmtpServer;
        private string _MailFromAddress;
        private bool _TestMode;
        private string _TestSmtpServer;
        private string _TestMailFromAddress;
        private string _TestMailToAddress;
        #endregion

        public EmailManager()
        {
            //Load Mail Settings from Web.Config
            if (HttpContext.Current.Request.Url.AbsoluteUri.ToString().IndexOf("localhost") > -1)
                _SmtpServer = "localhost";
            else
                _SmtpServer = ConfigurationSettings.AppSettings["SmtpServer"];
            //   
            _MailFromAddress = ConfigurationSettings.AppSettings["MailFromAddress"];
            _TestMode = Convert.ToBoolean(ConfigurationSettings.AppSettings["TestMode"]);
            _TestSmtpServer = ConfigurationSettings.AppSettings["TestSmtpServer"];
            _TestMailFromAddress = ConfigurationSettings.AppSettings["TestMailFromAddress"];
            _TestMailToAddress = ConfigurationSettings.AppSettings["TestMailToAddress"];
            //  _TestMailToAddress = "kittikiat.wattnasangmeechai@kcc.com";
        }

        public void SendMail(string toAddress, string subject, string body)
        {
            SendMail(toAddress, subject, body, _MailFromAddress);
        }
        public void SendMail(string toAddress, string subject, string body, string fromAddress)
        {
            if (string.IsNullOrEmpty(toAddress) == false)
            {
                MailAddressCollection mac = new MailAddressCollection();
                mac.Add(toAddress);
                SendMail(mac, subject, body, new MailAddress(fromAddress));
            }
        }

        public void SendMail(List<string> toAddresslist, string subject, string body, string fromAddress)
        {
            MailAddressCollection mac = new MailAddressCollection();
            foreach (string toAddress in toAddresslist)
            {
                if (string.IsNullOrEmpty(toAddress) == false)
                {
                    mac.Add(toAddress);
                }
            }
            if (mac.Count > 0)
            {
                SendMail(mac, subject, body, new MailAddress(fromAddress));
            }

        }
        public void SendMail(MailAddressCollection toAddresses, string subject, string body, MailAddress fromAddress)
        {
            try
            {
                SmtpClient smtp = null;
                MailMessage mm = new MailMessage();

                mm.IsBodyHtml = true;
                mm.Priority = MailPriority.Normal;

                mm.Subject = subject;
                // mm.IsBodyHtml = true;
                //mm.BodyEncoding = System.Text.Encoding.UTF8;
                mm.Body = body;

                if (_TestMode)
                {
                    mm.From = new MailAddress(_TestMailFromAddress);
                    mm.To.Add(_TestMailToAddress);
                    smtp = new SmtpClient(_TestSmtpServer);
                    mm.Body = "<p>Test Mode E-mail: From:" + fromAddress.Address + "  To:" + toAddresses[0].Address + "</p>" + mm.Body;
                }
                else
                {
                    mm.From = fromAddress;
                    foreach (MailAddress toAddress in toAddresses)
                    {
                        mm.To.Add(toAddress);
                    }
                    smtp = new SmtpClient(_SmtpServer);
                }

                smtp.Send(mm);

            }
            catch (Exception ex)
            {

                throw;
            }
        }



    }
}